package io.keithlibrary.test;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class Program {
    public static void main(String[] args) {
        sample3();
        //sample2();
        //sample1();
    }

    public static void sample3(){
        GsonTest4 test1 = new GsonTest4();
        test1.setCtime(System.currentTimeMillis());
        test1.setUtime(System.currentTimeMillis() + 2000);
        test1.setDescription("deserialized to another class");
        test1.setName("test1");
        test1.setAppId(123465);

        Gson gson = new Gson();
        Type collectionType = new TypeToken<GsonTest3>(){}.getType();
        GsonTest3 test2 = deserTest(gson.toJson(test1), collectionType);

        System.out.println(gson.toJson(test2));
        System.out.println("sample 3 succeeded");
    }

    public static void sample2(){
        GsonTest1 test1 = new GsonTest1();
        test1.ctime = System.currentTimeMillis();
        test1.utime = System.currentTimeMillis() + 2000;
        test1.description = "deserialized to another class";
                test1.name = "test1";

        Gson gson = new Gson();
        Type collectionType = new TypeToken<GsonTest2>(){}.getType();
        GsonTest2 test2 = deserTest(gson.toJson(test1), collectionType);

        System.out.println(gson.toJson(test2));
        System.out.println("sample 2 succeeded");
    }

    public static void sample1(){
        Vector<String> list = new Vector<String>();
        //ArrayList<String> list = new ArrayList<String>();
        list.add("A");
        list.add("AB");
        list.add("ADC");

        Type collectionType = new TypeToken<Vector<String>>(){}.getType();
        Gson gson = new Gson();

        List<String> deserList = deserTest(gson.toJson(list));

        System.out.println(gson.toJson(deserList));
        System.out.println("sample 1 succeeded");
    }

    public static <T> T deserTest(String item){
        Gson gson = new Gson();
        Type collectionType = new TypeToken<T>(){}.getType();
        T result = gson.fromJson(item, collectionType);
        return result;
    }

    public static <T> T deserTest(String item, Type typeOfT){
        Gson gson = new Gson();
        T result = gson.fromJson(item, typeOfT);
        return result;
    }
}

